<template>
  <div>
    <el-breadcrumb separator="下的" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <h1>欢迎来到用户页面</h1>
    <el-card class="box-card" width="500px">
      <div>
        <el-row :gutter='20'>
          <el-col :span="9">
            <el-input clearable @clear='change' placeholder="请输入内容" v-model='queryinfo.query' class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click='change'></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="adduserDialogVisible=true" icon="el-icon-circle-plus-outline">添加用户
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="userlist" border stripe>
          <el-table-column prop="id" label="id" width="180">
          </el-table-column>
          <el-table-column prop="username" label="username" width="180">
          </el-table-column>
          <el-table-column prop="password" label="password" width="180">
          </el-table-column>
          <el-table-column prop="email" label="email" width="180">
          </el-table-column>
          <el-table-column prop="phone" label="phone" width="180">
          </el-table-column>
          <el-table-column prop="status" label="status" width="180">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" @change="updateStatus(scope.row)" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>

            </template>



          </el-table-column>
          <el-table-column prop="role" label="role" width="180">
          </el-table-column>
          <el-table-column prop="created" label="created" width="180">
          </el-table-column>
          <el-table-column prop="updated" label="updated" width="180">
          </el-table-column>
          <el-table-column prop="" label="操作" width="180">
            <template slot-scope="scope">



              <el-button type="primary" icon="el-icon-edit" size='small' @click="updateBtn(scope.row)"></el-button>
              <el-button type="danger" icon="el-icon-delete" size='small' @click="deleteBtn(scope.row)"></el-button>
            </template>
          </el-table-column>

        </el-table>
        <div class="block">
          <el-pagination @size-change="handlesizeChange" @current-change="handlecurrentChange"
            :current-page="queryinfo.pageNum" :page-sizes="[1, 2, 3, 4]" :page-size="queryinfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </el-card>

    <el-dialog title="用户新增" @close='closeAddUserDialog' :visible.sync="adduserDialogVisible" width="65%">
      <el-form :model="adduserForm" :rules="rules" ref="adduserRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="adduserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input type="password" v-model="adduserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认:" prop="password2">
          <el-input type="password" v-model="adduserForm.password2"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="adduserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model="adduserForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">

        <el-button @click="adduserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduserBtn">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="用户新增" @close='closeupdateDialog' :visible.sync="updateDialogVisible" width="65%">
      <el-form :model="updateUser" :rules="rules" ref="updateForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="id" prop="id">
          <el-input v-model="updateUser.id" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="updateUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model="updateUser.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">

        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateuserBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  /**/
  export default {
    data() {
      //校验邮箱规则
      const checkEmail = (rule, value, callback) => {
        //定义邮箱的正则表达式  JS中用/来表示正则表达式的开始和结束
        const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
        if (emailRege.test(value)) {
          //表示邮箱合法 正确返回
          return callback()
        }
        callback(new Error('请填写正确的邮箱地址'))
      }

      //校验手机号的邮箱规则
      const checkPhone = (rule, value, callback) => {

        //定义校验手机号的正则语法
        const phoneRege = /^1[^12][0-9]{9}$/
        if (phoneRege.test(value)) {

          return callback()
        }
        callback(new Error('请填写正确的手机号'))

      }
      const checkPass = (rule, value, callback) => {
        if (value != this.adduserForm.password)
          return callback(new Error("两次密码填写不一致"))
        else
          return callback()
      }
      return {
        queryinfo: {
          query: '',
          pageNum: 1,
          pageSize: 4
        },
        userlist: [{
          id: '',
          username: '',
          password: '',
          phone: '',
          email: '',
          status: true,
          role: '',
          created: '',
          updated: ''
        }],
        total: 0,
        adduserDialogVisible: false,
        adduserForm: {
          username: '',
          password: '',
          password2: '',
          phone: '',
          email: ''
        },
        updateUser: {
          id: '',
          phone: '',
          email: ''
        },
        rules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 8,
              message: '长度在 5 到 8 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 8,
              message: '长度在 5 到 8 个字符',
              trigger: 'blur'
            }
          ],
          password2: [{
              validator: checkPass,
              trigger: 'blur'
            },
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            }
          ],
          phone: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              min: 11,
              max: 11,
              message: '长度只能是11个字符',
              trigger: 'blur'
            },
            {
              validator: checkPhone,
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ]
        },
        updateDialogVisible: false
      }
    },
    methods: {
      async change() {
        //重新根据条件查找用户
        let {
          data: result
        } = await this.$http.get("/user/list", {
          params: this.queryinfo
        })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        this.userlist = result.data.row;
        this.total = result.data.total
      },
      handlesizeChange(val) {
        this.queryinfo.pageSize = val
        this.change()
      },
      handlecurrentChange(val) {
        this.queryinfo.pageNum = val
        this.change()
      },
      async updateStatus(user) {
        let {
          data: result
        } = await this.$http.put(`/user/status/${user.id}/${user.status}`)
        if (result.data > 0) {
          this.$message.success("成功啦")
        } else {
          this.$message.error("失败")
        }
      },
      closeAddUserDialog() {
        //重制表单
        this.$refs.adduserRuleForm.resetFields()
      },
      adduserBtn() {
        this.$refs.adduserRuleForm.validate(async valid => {
          if (!valid)
            return this.$message.error("请正确的填写信息")
          let {
            data: result
          } = await this.$http.post("/user/insert", this.adduserForm)
          if (result.status !== 200) {
            return this.$message.error("插入失败了，吊毛")
            adduserDialogVisible = false;
          } else {
            this.$message.success("成功了臭吊毛")
            this.change()
            this.adduserDialogVisible = false;
          }
        })
      },
      async deleteBtn(row) {
        let result = await this.$confirm(`此操作将永久删除用户${row.username}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
        console.log(result)
        if (result === 'confirm') {
          let result2 = await this.$http.delete("/user/delete/" + row.id)
          if (result2.status === 200) {
            this.$message.success("成功删除了一个憨批")
            this.change()
          } else {
            this.$message.error("你报错了，憨批")
          }
        } else {
          this.$message.info("用户取消删除")
        }

      },
      updateBtn(user) {
        this.updateDialogVisible = true
        this.updateUser.id = user.id
        this.updateUser.email = user.email
        this.updateUser.phone = user.phone
      },
      async updateuserBtn() {
        this.$refs.updateForm.validate(async valid => {
          if(!valid)
          return this.$message.error("请填写正确的信息")
          let {
            data: result
          } = await this.$http.put(
            `/user/update/${this.updateUser.id}/${this.updateUser.phone}/${this.updateUser.email}`)
          if (result.status !== 200)
            return this.$message.error("混蛋，报错了")
          this.$message.success("修改成功")
          this.updateDialogVisible = false
          this.change()
        })

      }

    },
    mounted() {
      this.change()
    }


  }
</script>

<style>
</style>
